﻿package com.alstudio.module.sns.weiboshare;
import java.io.File;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.sns.tencent.ITencent;
import com.alstudio.module.sns.tencent.ITencent.OnAuthEventListener;
import com.alstudio.utils.log.ALLog;
import com.loovee.imaohu.R;
import com.tencent.connect.share.QzoneShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

public class TencentShare implements IWeiboShare, ITencent.OnAuthEventListener {
	private static final String TAG = "TencentShare";
	private static ITencent mTencent;
	private Activity mActivity;
	private Callback mCallback;
	private String mContent;
	private String mImageFile;
	private boolean mIsAddMeach;
	private boolean mIsShare;
	private boolean mShareFlag;
	// private boolean mIsImageUploaded;
	// private boolean mIsDoingShare = false;

	private boolean mShareWithImageUrl = false;
	private String mImageUrl = "http://www.baibu.com";

	private boolean mReceiverRegistered = false;

	public TencentShare() {
	}

	public static ITencent getSinaWeibo() {
		return mTencent;
	}

	@Override
	public void authorize(Activity activity, Callback callback) {
		if (!mTencent.satisfyConditions()) {
			mShareFlag = false;
			mActivity = activity;
			mCallback = callback;
			authorize();
			return;
		}

		if (callback != null) {
			callback.onSuccess(IWeiboShare.ACTION_AUTHORIZE);
		}
	}

	@Override
	public void share(Activity activity, String content, String imageFile,
			boolean isAddMeach, Callback callback) {
		// if (mIsDoingShare)
		// return;

		// mIsDoingShare = true;
		mActivity = activity;
		mContent = content;
		mImageFile = imageFile;
		mIsAddMeach = isAddMeach;
		mIsShare = true;
		mCallback = callback;
		mShareWithImageUrl = false;
		mTencent = ThirdPartFactory.getTencentInstance(mActivity);
		if (!mTencent.satisfyConditions()) {
			mShareFlag = true;
			authorize();
			return;
		}
		doShare();
	}

	@Override
	public void shareWithImageUrl(Activity activity, String content,
			String imageUrl, boolean isAddMeach, Callback callback) {

		mActivity = activity;
		mContent = content;
		mIsAddMeach = isAddMeach;
		mIsShare = true;
		mCallback = callback;
		mShareWithImageUrl = true;
		mImageUrl = imageUrl;
		mTencent = ThirdPartFactory.getTencentInstance(mActivity);
		if (!mTencent.satisfyConditions()) {
			mShareFlag = true;
			authorize();
			return;
		}
		doShare();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

	}

	private void authorize() {
		mTencent.setOnAuthEventListener(this);
		mTencent.auth(mActivity, "all", this);

	}

	private void doShare() {
		
		boolean shareWithLocalImage = false;

		if (!mShareWithImageUrl) {
			if (!TextUtils.isEmpty(mImageFile)) {
				try {
					File file = new File(mImageFile);
					if (file.exists())
						shareWithLocalImage = true;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		if (shareWithLocalImage && !mTencent.satisfyConditions()) {
			mShareFlag = true;
			mIsShare = true;
			mIsAddMeach = true;
			authorize();
			return;
		}

		mActivity.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				if (mCallback != null) {
					mCallback.onStartShare();
				}
			}
		});

		try {

			if (mIsAddMeach) {
				mIsAddMeach = false;
				if (mCallback != null)
					mCallback.onSuccess(IWeiboShare.ACTION_FOLLOW);
			}

			if (mIsShare) {
				mIsShare = false;



				// shareCallback.onFail(100015, ""); // 测试用

				if (shareWithLocalImage) {
					ALLog.d("把你的分享图片上传到相册吧" + mImageFile);

					String content = mContent + " ";
					Bundle optionalArgs = new Bundle();
					optionalArgs.putString("photodesc", content);

					// if (!mTencent.uploadImage(mActivity, mImageFile,
					// optionalArgs, uploadImageCallback)) {
					//
					// }

					mTencent.uploadImage(mActivity, mImageFile, optionalArgs,
							uploadImageCallback);

				} else {
					ALLog.d("不分享图片吗？亲");
					doNormalShare();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doNormalShare() {
		String content = mContent + " "; /* WeiboShareUtil.getMyHomePageUrl() */

		ALLog.d("do normal QQ share : " + content);

		String imageUrl;
		if (!TextUtils.isEmpty(mImageUrl)) {
			imageUrl = mImageUrl;
		} else {
			imageUrl = WeiboShareUtil.getDefaultLooveeAppLogoUrl();
		}
		Bundle optionalArgs = new Bundle();
		optionalArgs.putString("photodesc", content);
		// mTencent.uploadImage(mActivity, imageUrl, optionalArgs,
		// uploadImageCallback);

		final Bundle params = new Bundle();
		params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,
				QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
		params.putString(QzoneShare.SHARE_TO_QQ_TITLE, ALLocalEnv.getLocalEnv().getString(R.string.app_name));
		params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, content);
		params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, imageUrl);
		// 支持传多个imageUrl
		ArrayList<String> imageUrls = new ArrayList<String>();
		imageUrls.add(imageUrl);
		params.putString(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrl);
		params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);
		doShareToQzone(params);
	}

	/**
	 * 用异步方式启动分享
	 * 
	 * @param params
	 */
	private void doShareToQzone(final Bundle params) {
		final Activity activity = mActivity;
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mTencent.getTencent().shareToQzone(activity, params,
						new IUiListener() {

							@Override
							public void onCancel() {
							}

							@Override
							public void onError(UiError e) {
								// TODO Auto-generated method stub

								uploadImageCallback.onAuthFailed(e.errorCode,
										e.errorDetail);
							}

							@Override
							public void onComplete(Object response) {
								// TODO Auto-generated method stub
								uploadImageCallback.doComplete(
										(JSONObject) response, null);
							}

						});
			}
		}).start();
	}

	private OnAuthEventListener uploadImageCallback = new OnAuthEventListener() {

		@Override
		public void onCancel() {

		}

		@Override
		public void onAuthSuccess() {

		}

		@Override
		public void onAuthFailed(int ret, String msg) {
			doNormalShare();
		}

		@Override
		public void doComplete(JSONObject response, Object state) {
			try {
				int ret = response.getInt("ret");
				if (ret == 0) {

					if (mCallback != null)
						mCallback.onSuccess(IWeiboShare.ACTION_SHARE);

				}
			} catch (JSONException e1) {
				e1.printStackTrace();
			}

			// String content = mContent + " "; // 最长36个中文字，超出部分会被截断。
			// Mylog.d(TAG, "QQ share : " + content);
			//
			// try {
			// String images = response.getString("large_url");
			// Map<String, String> optionalArgs = new HashMap<String, String>();
			// optionalArgs.put("summary", content); //
			// 所分享的网页资源的摘要内容，或者是网页的概要描述,
			// // 最长80个中文字，超出部分会被截断。
			// optionalArgs.put("images", images);
			// // mTencent.shareQZone(mActivity, content, mImageUrl,
			// // // optionalArgs, shareCallback);
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
		}
	};

	private OnAuthEventListener othCallback = new OnAuthEventListener() {

		@Override
		public void onCancel() {

		}

		@Override
		public void onAuthSuccess() {

		}

		@Override
		public void onAuthFailed(int ret, String msg) {

		}

		@Override
		public void doComplete(JSONObject response, Object state) {

		}

	};

	@Override
	public void onAuthSuccess() {

		doShare();
	}

	@Override
	public void getFriends(Activity activity, Callback callback) {

	}

	@Override
	public void onCancel() {

	}

	@Override
	public void onAuthFailed(int ret, String msg) {
	}

	@Override
	public void doComplete(JSONObject response, Object state) {
		try {
			int ret = response.getInt("ret");
			if (ret == 0) {

				// if (mCallback != null)
				// mCallback.onSuccess(IWeiboShare.ACTION_SHARE);
				doShare();
			}

			if (ret == 100013 || ret == 100014 || ret == 100015
					|| ret == 100016) {
				mTencent.setAccessToken("", "");
				doShare();

				if (mCallback != null)
					mCallback.onFailed(IWeiboShare.ACTION_SHARE);
				return;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
